/*   
 * �ļ�����FinanceServiceImpl.java
 * ��Ȩ����Copy Ruantu��  
 * ��������������  
 * �޸��ˣ���MengFanding�� 
 * �޸�ʱ�䣺2017 ����2:33:54
 * �޸ĵ��ţ����޸ĵ��š�  
 * �޸����ݣ����޸����ݡ�  
 */

package com.ruantu.clothing.service.finance.impl;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

import com.ruantu.clothing.dao.finance.PeriodMapper;
import com.ruantu.clothing.entity.KeHu;
import com.ruantu.clothing.entity.YearAndSeason;
import com.ruantu.clothing.entity.ZZMX;
import com.ruantu.clothing.entity.report.Foot;
import com.ruantu.clothing.util.PrimaryGenerater;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ruantu.clothing.dao.finance.FinanceMapper;
import com.ruantu.clothing.dao.finance.FinanceRecordMapper;
import com.ruantu.clothing.dao.finance.FinanceTransactionMapper;
import com.ruantu.clothing.entity.PageBean;
import com.ruantu.clothing.entity.finance.Finance;
import com.ruantu.clothing.entity.finance.FinanceRecord;
import com.ruantu.clothing.entity.finance.FinanceTransaction;
import com.ruantu.clothing.entity.finance.Period;
import com.ruantu.clothing.service.finance.FinanceService;
import com.ruantu.clothing.util.Time;
import com.ruantu.clothing.util.UUIDUtil;

/**
 * FinanceServiceImpl
 */
@Service
public class FinanceServiceImpl implements FinanceService {

    @Autowired
    private FinanceRecordMapper financeRecordMapper;

    @Autowired
    private FinanceMapper financeMapper;

    @Autowired
    private FinanceTransactionMapper financeTransactionMapper;

    @Autowired
    private PeriodMapper pdMapper;

    @Override
    @Transactional
    public boolean startNewPeriod(String name) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("name", name);

        Period p = financeMapper.findPeriodByName(map);
        if (p != null)
            throw new RuntimeException("无账期!");

        map.put("starttimestamp", System.currentTimeMillis());
        int i = financeMapper.addNewPeriod(map);
        if (i > 0)
            return true;
        return false;
    }

    @Override
    public List<Period> showPeriodList() {
        List<Period> list = financeMapper.findAllPeriod();
        return list;
    }

    @Override
    @Transactional
    public FinanceRecord addFinanceRecord(FinanceRecord record) {

        String wldwid = record.getWldw();
        Finance finance = getNearFinance(wldwid, record.getWldwType(), record.getGsjg());
        finance.setAmount(finance.getAmount() + record.getAmount());
        finance.setEndMoney(finance.getEndMoney() + record.getAmount());
        financeMapper.updateByPrimaryKeySelective(finance);
        record.setId(UUIDUtil.getUUID());
        record.setTime(new Date());
        record.setFinanceid(finance.getId());
        record.setLsh(getLSHByJgid(record.getGsjg()));
        financeRecordMapper.insertSelective(record);


        return record;
    }

    public synchronized String getLSHByJgid(String jgid) {
        String lsh = Time.toyyyyMMdd(new Date());
        String maxLsh = financeRecordMapper.selectTodayMaxLSHByJG(jgid);
        if (maxLsh == null) {
            lsh += "000001";
        } else {
            Long num = Long.valueOf(maxLsh.substring(8));
            lsh += to6Len(++num);
        }
        return lsh;
    }

    public String to6Len(Number num) {
        String result = "";
        for (int i = 0; i < 6 - num.toString().length(); i++) {
            result += "0";
        }
        result += num;
        return result;
    }

    /**
     * 获得总表中记录
     *
     * @param wldwid
     * @param
     * @return
     */
    private Finance getNearFinance(String wldwid, Integer wldwType, String gsjg) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("wldwid", wldwid);
        params.put("wldwType", wldwType);
        params.put("jgid", gsjg);
        Finance finance = financeMapper.findByWldwFinance(params);// 1.查询总表中是否存在该单位的往来信息
        if (finance == null) {
            finance = new Finance();
            finance.setId(UUIDUtil.getUUID());
            Finance nearFinance = findNearFinance(wldwid, wldwType, gsjg);//找到最近一次交易总表中期末金额
            if (nearFinance != null) {
                finance.setStartMoney(nearFinance.getEndMoney());
            }

            Period activePeriod = financeMapper.activePeriod();
            finance.setJgid(gsjg);
            finance.setPeriodid(activePeriod.getId());

            finance.setWldwid(wldwid);
            finance.setWldwType(wldwType);

            financeMapper.insertSelective(finance);
        }
        return finance;
    }

    private Finance findNearFinance(String wldwid, Integer wldwType, String gsjg) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("wldwid", wldwid);
        map.put("wldwType", wldwType);
        map.put("jgid", gsjg);
        Finance nearFinance = financeMapper.findByNearFinance(map);
        return nearFinance;
    }

    @Override
    public List<Finance> findThisPeriod(String jgid) {
        Period activePeriod = financeMapper.activePeriod();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("jgid", jgid);
        map.put("periodid", activePeriod.getId());
        List<Finance> list = financeMapper.findJgPeriodFinance(map);
        return list;
    }

    @Override
    public List<FinanceRecord> findByFinanceKey(String id, PageBean page) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", id);
        if (page == null)
            page = new PageBean();
        map.put("start", page.getStart());
        map.put("rows", page.getRows());

        page.setTotal(financeRecordMapper.selectListByFinanceKeyCount(map));

        return financeRecordMapper.selectListByFinanceKey(map);
    }

    @Override
    public List<Finance> findFinancePeriod(String jgid, String periodId, PageBean page) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("jgid", jgid);
        map.put("periodid", periodId);
        if (page == null)
            page = new PageBean();
        map.put("start", page.getStart());
        map.put("rows", page.getRows());
        List<Finance> list = financeMapper.findJgPeriodFinance(map);
        page.setTotal(financeMapper.findJgPeriodFinanceCount(map));
        return list;
    }

    @Override
    @Transactional
    public boolean payOrReceive(FinanceTransaction transaction) {
        // 1. 收付款流程一致
        // 2. 只要红蓝单标记为正负1
        // 3. 交易金额X红蓝标记
        Finance f = getNearFinance(transaction.getWldwid(), transaction.getWldwtype(), transaction.getGsjg());
        // FIXME 要更新哪些钱
        f.setPaid(f.getPaid() + (transaction.getHl() * transaction.getMoney()));
        if (transaction.getYh_money() == null) {
            transaction.setYh_money(0.00);
        }
        f.setCheap(f.getCheap() + (transaction.getHl() * transaction.getYh_money()));
        financeMapper.updateByPrimaryKeySelective(f);
        transaction.setId(UUIDUtil.getUUID());
        transaction.setTranTime(new Date());
        int hashCodeV = UUID.randomUUID().toString().hashCode();
        if (hashCodeV < 0) {//有可能是负数
            hashCodeV = -hashCodeV;
        }
        transaction.setLdid(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + String.format("%011d", hashCodeV));
        financeTransactionMapper.insertSelective(transaction);
        return true;
    }

    @Override
    public List<FinanceTransaction> findByLSHPage(Integer hl, String lsh, String gsjg, PageBean page) {
        if (page == null)
            page = new PageBean();
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("hl", hl);
        params.put("lsh", lsh);
        params.put("gsjg", gsjg);
        params.put("start", page.getStart());
        params.put("rows", page.getRows());
        page.setTotal(financeTransactionMapper.selectByLSHGSJGPeriodPageCount(params));
        List<FinanceTransaction> list = financeTransactionMapper.selectByLSHGSJGPeriodPage(params);
        return list;
    }

    @Override
    public List<KeHu> selectAllKeHuService() {

        return financeMapper.selectAllKeHu();
    }

    @Override
    public List<Period> selectPeriodListService() {
        return pdMapper.selectPeriodList();
    }


    /***
     * 获得总账
     * @param page
     * @return
     */
    @Override
    public List<Finance> selectZZReportListService(PageBean page) {
        Map<String, Object> mapCan = new HashMap<>();
        mapCan.put("order", page.getOrder());
        mapCan.put("sort", page.getSort());
        mapCan.put("key", page.getKey());
        mapCan.put("jgId", page.getJgId());
        mapCan.put("periodId", page.getPeriodId());
        mapCan.put("start", page.getStart());
        mapCan.put("pageSize", page.getRows());
        page.setTotal(financeMapper.selectZZReportCount(mapCan));
        return financeMapper.selectZZReportList(mapCan);
    }

    /***
     * 总账导出
     * @param page
     * @return
     */
    @Override
    public HSSFWorkbook selectZZReportListDaoChuService(PageBean page) {
        Map<String, Object> mapCan = new HashMap<>();
        mapCan.put("key", page.getKey());
        mapCan.put("jgId", page.getJgId());
        mapCan.put("periodId", page.getPeriodId());
        page.setTotal(financeMapper.selectZZReportCount(mapCan));
        List<Finance> list = financeMapper.selectZZReportListDaoChu(mapCan);
        int lie = 0;
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet("sheet1");
        sheet.setColumnWidth(0, 20 * 256);
        HSSFRow row = sheet.createRow(0);
        HSSFCellStyle style = wb.createCellStyle();//
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);//
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//
        HSSFCell cell = row.createCell(0);
        cell.setCellValue("往来单位");
        cell = row.createCell(++lie);
        cell.setCellValue("往来单位类型");
        cell = row.createCell(++lie);
        cell.setCellValue("期初金额");
        cell = row.createCell(++lie);
        cell.setCellValue("本期交易金额");
        cell = row.createCell(++lie);
        cell.setCellValue("已收金额");
        cell = row.createCell(++lie);
        cell.setCellValue("欠款");
        cell = row.createCell(++lie);
        cell.setCellValue("优惠金额");
        cell = row.createCell(++lie);
        sheet.setColumnWidth(lie, 10 * 800);
        for (int i = 0; i < list.size(); i++) {
            lie = 0;
            row = sheet.createRow(i + 1);
            row.createCell(lie).setCellValue(list.get(i).getWldwName());
            if(list.get(i).getKhtype()==0){
                row.createCell(++lie).setCellValue("批发");
            }else if(list.get(i).getKhtype()==1){
                row.createCell(++lie).setCellValue("分销");
            }else if(list.get(i).getKhtype()==2){
                row.createCell(++lie).setCellValue("零售客户");
            }else if(list.get(i).getKhtype()==3){
                row.createCell(++lie).setCellValue("供应商");
            }else{
                row.createCell(++lie).setCellValue("其他");
            }
            row.createCell(++lie).setCellValue(list.get(i).getStartMoney());
            row.createCell(++lie).setCellValue(list.get(i).getAmount());
            row.createCell(++lie).setCellValue(list.get(i).getPaid());
            row.createCell(++lie).setCellValue(list.get(i).getPaid() - list.get(i).getAmount());
            row.createCell(++lie).setCellValue(list.get(i).getCheap());
            cell = row.createCell(++lie);
            cell.setCellStyle(style);
        }
        return wb;

    }


    /***
     * 获得总账明细
     * @param page
     * @return
     */
    @Override
    public List<ZZMX> selectZZMXReportListService(PageBean page) {
        Map<String, Object> mapCan = new HashMap<>();
        mapCan.put("jgId", page.getJgId());
        mapCan.put("periodId", page.getPeriodId());
        mapCan.put("wldwId", page.getWldwId());
        mapCan.put("financeId", page.getFinanceId());
        mapCan.put("start", page.getStart());
        mapCan.put("pageSize", page.getRows());
        mapCan.put("nj", page.getNj());
        mapCan.put("stime", page.getStime());
        mapCan.put("etime", page.getEtime());
        page.setTotal(financeMapper.selectZZMXReportCount(mapCan));
        return financeMapper.selectZZMXReportList(mapCan);
    }

    @Override
    public HSSFWorkbook selectZZMXReportListDaoChuServicer(PageBean page) {
        Map<String, Object> mapCan = new HashMap<>();
        mapCan.put("jgId", page.getJgId());
        mapCan.put("periodId", page.getPeriodId());
        mapCan.put("wldwId", page.getWldwId());
        mapCan.put("financeId", page.getFinanceId());
        mapCan.put("nj", page.getNj());
        mapCan.put("stime", page.getStime());
        mapCan.put("etime", page.getEtime());
        List<ZZMX> list = financeMapper.selectZZMXReportListDaoChu(mapCan);

        int lie = 0;
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet("sheet1");
        sheet.setColumnWidth(0, 20 * 256);
        HSSFRow row = sheet.createRow(0);
        HSSFCellStyle style = wb.createCellStyle();//
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);//
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//
        HSSFCell cell = row.createCell(0);
        cell.setCellValue("往来单位");
        cell = row.createCell(++lie);
        cell.setCellValue("往来单位类型");
        cell = row.createCell(++lie);
        cell.setCellValue("所属年季");
        cell = row.createCell(++lie);
        cell.setCellValue("类型");
        cell = row.createCell(++lie);
        cell.setCellValue("总数");
        cell = row.createCell(++lie);
        cell.setCellValue("金额");
        cell = row.createCell(++lie);
        cell.setCellValue("时间");
        cell = row.createCell(++lie);
        sheet.setColumnWidth(lie, 10 * 800);

        for (int i = 0; i < list.size(); i++) {
            lie = 0;
            row = sheet.createRow(i + 1);
            row.createCell(lie).setCellValue(list.get(i).getWldwName());
            if(list.get(i).getKhtype()==0){
                row.createCell(++lie).setCellValue("批发");
            }else if(list.get(i).getKhtype()==1){
                row.createCell(++lie).setCellValue("分销");
            }else if(list.get(i).getKhtype()==2){
                row.createCell(++lie).setCellValue("零售客户");
            }else if(list.get(i).getKhtype()==3){
                row.createCell(++lie).setCellValue("供应商");
            }else{
                row.createCell(++lie).setCellValue("其他");
            }
            row.createCell(++lie).setCellValue(list.get(i).getYearandseason());

            if (list.get(i).getFslx() != null) {
                row.createCell(++lie).setCellValue(list.get(i).getFslx());
            } else {
                if (list.get(i).getHl() == 1) {
                    row.createCell(++lie).setCellValue("收账");
                } else if (list.get(i).getHl() == -1) {
                    row.createCell(++lie).setCellValue("出账");
                }
            }

            if (list.get(i).getZshuliang() != null) {
                row.createCell(++lie).setCellValue(list.get(i).getZshuliang());
            } else {
                row.createCell(++lie).setCellValue("");
            }

            row.createCell(++lie).setCellValue(list.get(i).getAmount());
            row.createCell(++lie).setCellValue(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(list.get(i).getTime()));
            cell = row.createCell(++lie);
            cell.setCellStyle(style);
        }
        return wb;
    }


    /**
     * 根据机构jgid查询
     *
     * @param jgid
     * @return
     */
    @Override
    public List<FinanceTransaction> selectByJgid(String jgid) {

        return financeTransactionMapper.selectByJgid(jgid);
    }

    /***
     * 获得年季
     * @return
     */

    @Override
    public List<YearAndSeason> findNAJ(String jgId) {
        return financeTransactionMapper.findNAJ(jgId);
    }


    /***
     * 对账单
     * @param page
     * @return
     */
    @Override
    public List<ZZMX> financeAccountService(PageBean page) {
        Map<String, Object> map = new HashMap<>();
        map.put("nj", page.getNj());
        map.put("fslx", page.getFslx());
        map.put("key", page.getKey());
        map.put("stime", page.getStime());
        map.put("etime", page.getEtime());
        map.put("jgId",page.getJgId());
        map.put("start", page.getStart());
        map.put("pageSize", page.getRows());

        Foot foot=financeMapper.financeAccountCount(map);
        if(foot!=null){
            foot.setProduct("总计:");
        }
        page.setFoot(foot);
        return financeMapper.financeAccount(map);
    }

    /****
     * 导出对账单
     * @param page
     * @return
     */
    @Override
    public HSSFWorkbook financeAccountReportService(PageBean page) {
        Map<String, Object> map = new HashMap<>();
        map.put("nj", page.getNj());
        map.put("fslx", page.getFslx());
        map.put("key", page.getKey());
        map.put("stime", page.getStime());
        map.put("etime", page.getEtime());
        map.put("jgId",page.getJgId());
        map.put("start", page.getStart());
        map.put("pageSize", page.getRows());
        List<ZZMX> list=financeMapper.financeAccountReport(map);
        int lie = 0;
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet("sheet1");
        sheet.setColumnWidth(0, 20 * 256);
        HSSFRow row = sheet.createRow(0);
        HSSFCellStyle style = wb.createCellStyle();//
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);//
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//
        HSSFCell cell = row.createCell(0);
        cell.setCellValue("流水号");
        cell = row.createCell(++lie);
        cell.setCellValue("原订单号");
        cell = row.createCell(++lie);
        cell.setCellValue("往来单位");
        cell = row.createCell(++lie);
        cell.setCellValue("往来单位类型");
        cell = row.createCell(++lie);
        cell.setCellValue("所属年季");
        cell = row.createCell(++lie);
        cell.setCellValue("类型");
        cell = row.createCell(++lie);
        cell.setCellValue("交易金额");
        cell = row.createCell(++lie);
        cell.setCellValue("交易总数");
        cell = row.createCell(++lie);
        cell.setCellValue("已付金额");
        cell = row.createCell(++lie);

        cell.setCellValue("日期");
        cell = row.createCell(++lie);
        cell.setCellValue("备注");
        cell = row.createCell(++lie);
        sheet.setColumnWidth(lie, 10 * 800);

        for(int i=0;i<list.size();i++){
            lie=0;
            row = sheet.createRow(i + 1);
            row.createCell(lie).setCellValue(list.get(i).getLsh());
            row.createCell(++lie).setCellValue(list.get(i).getYddid());
            row.createCell(++lie).setCellValue(list.get(i).getWldwName());
            if(list.get(i).getKhtype()==0){
                row.createCell(++lie).setCellValue("批发");
            }else if(list.get(i).getKhtype()==1){
                row.createCell(++lie).setCellValue("分销");
            }else if(list.get(i).getKhtype()==2){
                row.createCell(++lie).setCellValue("零售客户");
            }else if(list.get(i).getKhtype()==3){
                row.createCell(++lie).setCellValue("供应商");
            }else{
                row.createCell(++lie).setCellValue("其他");
            }
            row.createCell(++lie).setCellValue(list.get(i).getYearandseason());
            if("1".equals(list.get(i).getFslx())){
                row.createCell(++lie).setCellValue("进账");

            }else if("-1".equals(list.get(i).getFslx())){
                row.createCell(++lie).setCellValue("出账");
            }else{
                row.createCell(++lie).setCellValue(list.get(i).getFslx());
            }
            row.createCell(++lie).setCellValue(list.get(i).getAmount());
            row.createCell(++lie).setCellValue(list.get(i).getZshuliang());
            row.createCell(++lie).setCellValue(list.get(i).getZshuliang());
            row.createCell(++lie).setCellValue(list.get(i).getMoney());
            row.createCell(++lie).setCellValue(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(list.get(i).getTime()));
            row.createCell(++lie).setCellValue(list.get(i).getMark());

            cell = row.createCell(++lie);
            cell.setCellStyle(style);
        }


        return wb;
    }

}
